package com.sunday.android.fangdaifu.bukong.activity.index;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.sunday.android.fangdaifu.bukong.BaseApp;
import com.sunday.android.fangdaifu.bukong.R;
import com.sunday.android.fangdaifu.bukong.adapter.ProjectListWithHeadersAdapter;
import com.sunday.android.fangdaifu.bukong.entity.ProjectListItem;
import com.sunday.android.fangdaifu.bukong.entity.event.SelectProject;
import com.sunday.android.fangdaifu.bukong.http.ApiClient;
import com.sunday.android.fangdaifu.bukong.utils.Constants;
import com.sunday.android.fangdaifu.bukong.utils.sidebar.QuickSideBarTipsView;
import com.sunday.android.fangdaifu.bukong.utils.sidebar.QuickSideBarView;
import com.sunday.android.fangdaifu.bukong.utils.sidebar.listener.OnQuickSideBarTouchListener;
import com.sunday.android.fangdaifu.bukong.utils.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.member.base.BaseActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProjectListActivity extends BaseActivity implements OnQuickSideBarTouchListener {

    @Bind(R.id.etSearch)
    EditText etSearch;
    @Bind(R.id.imgSearch)
    ImageView imgSearch;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.quickSideBarTipsView)
    QuickSideBarTipsView quickSideBarTipsView;
    @Bind(R.id.quickSideBarView)
    QuickSideBarView quickSideBarView;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @Bind(R.id.emptylayout)
    EmptyLayout emptyLayout;

    private String searchContent;
    private List<ProjectListItem> itemList = new ArrayList<>();
    private List<ProjectListItem.ListBean> beanList = new ArrayList<>();
    private ArrayList<String> customLetters = new ArrayList<>();
    private HashMap<String,Integer> letters = new HashMap<>();
    private long memberId;
    private ProjectListWithHeadersAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project_list);
        ButterKnife.bind(this);
        memberId = BaseApp.getInstance().getMemberId();
        initView();
        getData();
    }

    private void initView(){
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new ProjectListWithHeadersAdapter(mContext,beanList);
        recyclerView.setAdapter(adapter);
        final StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(adapter);
        recyclerView.addItemDecoration(headersDecor);
        quickSideBarView.setOnQuickSideBarTouchListener(this);
        etSearch.setOnKeyListener(onKeyListener);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });
        adapter.setSelectItem(new ProjectListWithHeadersAdapter.SelectItem() {
            @Override
            public void selectItem(int position, ProjectListItem.ListBean bean) {
                intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean",bean);
                intent.putExtra("bean",bundle);
                setResult(Constants.SELECT_PROJECT_ITEM_RESULT,intent);
                ProjectListActivity.this.finish();
            }
        });
    }

    private void loading(){
        if (!refreshLayout.isRefreshing()){
            refreshLayout.setRefreshing(true);
        }
    }

    private void getData(){
        loading();
        Call<ResultDO<List<ProjectListItem>>> call = ApiClient.getApiAdapter().BbProjectList(memberId,searchContent);
        call.enqueue(new Callback<ResultDO<List<ProjectListItem>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<ProjectListItem>>> call, Response<ResultDO<List<ProjectListItem>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    itemList.clear();
                    beanList.clear();
                    itemList.addAll(response.body().getResult());
                    if (itemList.isEmpty()){
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                        emptyLayout.setErrorMessage("暂无数据");
                    }else {
                        emptyLayout.setVisibility(View.GONE);
                    }
                    ProjectListItem item = null;
                    for (int i = 0;i<itemList.size();i++){
                        item = itemList.get(i);
                        beanList.addAll(item.getList());
                        //如果没有这个key则加入并把位置也加入
                        if(!letters.containsKey(item.getEnStr())){
                            letters.put(item.getEnStr(),i);
                            customLetters.add(item.getEnStr());
                        }
                    }
                    quickSideBarView.setLetters(customLetters);
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<ProjectListItem>>> call, Throwable t) {
                if (isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
            }
        });
    }

    @OnClick(R.id.imgSearch)
    public void onViewClicked() {
        searchContent = etSearch.getText().toString().trim();
        getData();
    }

    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){
                searchContent = etSearch.getText().toString().trim();
                getData();
                return true;
            }
            return false;
        }
    };

    @Override
    public void onLetterChanged(String letter, int position, float y) {
        quickSideBarTipsView.setText(letter, position, y);
        //有此key则获取位置并滚动到该位置
        if(letters.containsKey(letter)) {
            recyclerView.scrollToPosition(letters.get(letter));
        }
    }

    @Override
    public void onLetterTouching(boolean touching) {
        quickSideBarTipsView.setVisibility(touching? View.VISIBLE:View.INVISIBLE);
    }
}
